<template>
  <div>
    <el-row type="flex" justify="center" align="middle">
      <el-steps :active="active" finish-status="success" align-center style="margin-top: 20px;width: 60%">
        <el-step title="选取文件" icon="el-icon-edit" description="请选取只包含图片的文件夹" />
        <el-step title="提交处理" icon="el-icon-upload" description="图像预处理+虫害特征提取+分类统计" />
        <el-step title="预览结果" icon="el-icon-s-claim" description="查看虫情详情" />
      </el-steps>
    </el-row>
    <el-divider><i class="el-icon-view" />虫情热点分布</el-divider>
    <el-row type="flex" justify="center" align="middle">
      <el-col :span="15">
        <div class="progress_block">
          <el-image :src="base64_image_preview" style="display:flex; flex-flow:column; align-items: center;justify-content: center">
            <div slot="error" class="image-slot">
              <transition name="el-zoom-in-center">
                <Heatmap v-if="!show_progress" ref="heatmap" :img_src="heatmap_bg" :data_source="latest_insects_info" />
              </transition>
              <div class="task-visual-area">
                <transition name="el-fade-in-linear">
                  <div v-if="show_progress" style="display: flex;flex-flow: column; align-items: center;justify-content: center">
                    <el-progress :text-inside="true" :stroke-width="26" :percentage="processing_progress" :color="progressbar_style" style="width: 300px" />
                    <el-tag style="text-align: center">{{ progress_indicator }}</el-tag>
                  </div>
                </transition>
              </div>
            </div>
          </el-image>
        </div>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center" align="middle">
      <el-col :span="15">
        <div class="control-area">
          <el-tooltip content="反馈结果，让我们做得更好~" placement="top" effect="light">
            <el-rate
              v-model="value"
              :icon-classes="iconClasses"
              show-text
              void-icon-class="icon-rate-face-off"
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            />
          </el-tooltip>
          <el-button type="primary" icon="el-icon-folder-opened" style="margin-left: 50px;" @click="table = true">打开系统目录</el-button>
        </div>
      </el-col>
    </el-row>
    <el-divider><i class="el-icon-s-order" />历史统计结果</el-divider>
    <InsectsInfoTable ref="insectsinfotable" @getSelectedInsectsInfo="setHeatmapDatasource" />
    <el-drawer
      :visible.sync="table"
      direction="rtl"
      size="70%"
    >
      <div slot="title"><el-tag style="font-size: 15px"><i class="el-icon-folder-opened" />请选择粘虫板图像存放文件夹</el-tag></div>
      <el-button class="submit-bt" type="primary" icon="el-icon-success" :loading="show_progress" @click="startProcessing">提交</el-button>
      <el-tooltip placement="bottom" effect="light">
        <div slot="content">请选择只包含病虫害原图的文件夹<br>预处理后的图片默认保存路径为：<br>insects_detection→processed_img→原图文件夹名~</div>
        <i class="el-icon-info" style="color: rgba(65,192,42,0.86);margin-left: 20px" />
      </el-tooltip>
      <file-view @getSelectedFile="getFilePath" />
    </el-drawer>
  </div>
</template>
<script>
import '@/assets/custom-theme/fonts/styles.css'
import FileView from '@/views/i18n-demo/index'
import InsectsInfoTable from '@/views/control-panel/components/insects-info-table'
import { update_insects_info, query_task_progress, query_recent_insects_info } from '@/api/remote-search'
import Heatmap from '@/views/dashboard/admin/components/Heatmap'
export default {
  components: { Heatmap, InsectsInfoTable, FileView },
  data() {
    return {
      selected_file: '',
      table: false,
      dialog: false,
      loading: false,
      heatmap_bg: require('@/assets/images/farm.jpg'),
      processing_progress: 0,
      show_progress: false,
      progress_indicator: 'just_started...',
      progress_stages: 'PENDING',
      progress_query_limits: 5,
      progress_query_times: 0,
      switch_flag: 0,
      progressbar_style: 'default',
      base64_image_preview: '',
      active: 0,
      value: null,
      iconClasses: ['icon-rate-face-1', 'icon-rate-face-2', 'icon-rate-face-3'],
      recent_insects_info: [],
      latest_insects_info: {
        each_board_info: {
          board: '1-1-1',
          飞虱: 0,
          蓟马: 0
        }
      },
      single_board_info: [{
        board: '加载中...',
        飞虱: '加载中...',
        蓟马: '加载中...'
      }]
    }
  },
  mounted() {
    this.getRecentInsectsInfo()
  },
  methods: {
    switchStyle() {
      if (this.progress_stages === 'IMAGE_PREPROCESS_PROGRESS') {
        this.progressbar_style = '#409eff'
      } else if (this.progress_stages === 'CHARACTER_EXTRACTION_PROGRESS') {
        this.progressbar_style = '#5cb87a'
      }
    },
    formatter(row, column) {
      return row.address
    },
    getFilePath(payload) {
      this.selected_file = payload
      this.active = 1
      // console.log(this.selected_file)
    },
    getRecentInsectsInfo() {
      query_recent_insects_info().then(res => {
        this.recent_insects_info = res.data
        // this.latest_insects_info = res.data[res.data.length-1]
        // console.log(res.data)
      })
    },
    setHeatmapDatasource(data_source) {
      this.latest_insects_info = data_source
      // console.log(this.latest_insects_info)
      this.$refs.heatmap.repaint_heatmap(this.latest_insects_info)
    },
    showDetail(index, row) {
      // console.log(row.each_board_info)
      this.single_board_info = row.each_board_info
    },
    startProcessing() {
      const supported_filetype = ['文件夹']
      if (this.selected_file === '') {
        this.$message({
          type: 'warning',
          message: '请至少选择一个存放粘虫板原相的文件夹~'
        })
      } else if (supported_filetype.indexOf(this.selected_file.filetype) < 0) {
        this.$message({
          type: 'warning',
          message: '请选择文件夹，不要选取单个文件~'
        })
      } else {
        this.active++
        update_insects_info(this.selected_file.fullname)
          .then(response => {
            // console.log(response)
            if (response.message === 'Task submitted') {
              this.$message({
                type: 'success',
                message: '正在计算中，请稍等片刻...'
              })
              this.updateProgressBar(response.data.task_monitor)
            } else {
              this.$message({
                type: 'error',
                message: '计算失败，请检查网络设置~'
              })
            }
          })
      }
    },
    handleDelete() {
      this.$message({
        message: '请联系开发人员获取相关权限',
        type: 'warning'
      })
    },
    updateProgressBar(task_url) {
      const that = this
      this.show_progress = true
      query_task_progress(task_url)
        .then(response => {
          // console.log(response.data)
          that.processing_progress = parseInt(response.data.current / response.data.total * 100)
          that.progress_indicator = response.data['status']
          that.progress_stages = response.data['state']
          that.switchStyle()
          if (response.data['state'] === 'SUCCESS') {
            if ('result' in response.data) {
              // console.log(response.data['result'])
              that.latest_insects_info = response.data['result']
              that.$refs.insectsinfotable.getRecentInsectsInfo()
              that.$message({
                type: 'success',
                message: '处理成功~'
              })
              setTimeout(function() {
                that.show_progress = false
              }, 1500)
              setTimeout(function() {
                that.$refs.heatmap.repaint_heatmap()
              }, 1000)
              that.active++
            } else {
              // 意料之外的事情发生
              that.progress_indicator = 'Ooooops...something bad happened!, the current task returns no result~'
            }
          } else {
            setTimeout(function() {
              if (response.data['state'] === 'PENDING') {
                that.progress_query_times += 1
                // console.log(that.progress_query_times)
              }
              if (that.progress_query_times < that.progress_query_limits) {
                that.updateProgressBar(task_url)
              } else {
                that.$message({
                  type: 'error',
                  message: '任务长时间未能处理，请稍后重试...'
                })
                that.show_progress = false
                return
              }
            }, 1000)
          }
        })
    }
  }
}
</script>
<style lang="scss">
.el-drawer.rtl {
  overflow: scroll
}
.sub-title{
  width: 100%;
  text-align: center;
  margin-bottom: 10px;
}
.submit-bt{
  margin-left: 20px;
}
.progress_block{
  margin: 20px;
  display: flex;
  height: 466px;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  .el-image{
    width: 100%;
    height: 100%;
  }
}
.image-view-area{
  //margin-top: 40px;
}
.control-area{
  display: flex;
  justify-content: center;
  margin-top: 20px;
  margin-bottom: 20px;
  align-items: center;
}
.task-visual-area{
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
